package com.xbfinance.common.util;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class FdsfUtils {
    static {
        try {
            ClientGlobal.init("fdfs_client.conf");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        System.out.println("ClientGlobal.configInfo(): " + ClientGlobal.configInfo());
    }

    public static String fdsfUpload(MultipartFile file) {
        String url = "";
        if(file.isEmpty()){
            return url;
        }
        String tempFileName = file.getOriginalFilename();
        String fileExtName = tempFileName.substring(tempFileName.lastIndexOf("."));
        //建立连接
        TrackerClient tracker = new TrackerClient();
        TrackerServer trackerServer = null;
        try {
            trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            //设置元信息
            NameValuePair[] metaList = new NameValuePair[3];
            metaList[0] = new NameValuePair("fileName", tempFileName);
            metaList[1] = new NameValuePair("fileExtName", fileExtName);
            metaList[2] = new NameValuePair("fileLength", String.valueOf(file.getSize()));
            byte[] fileBuff = file.getBytes();
            url = client.upload_file1(fileBuff, fileExtName, metaList);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return url;
    }
}
